package cn.edu.zut.hkxy.service.impl;

import cn.edu.zut.hkxy.mapper.FeatureMapper;
import cn.edu.zut.hkxy.pojo.Feature;
import cn.edu.zut.hkxy.pojo.FeatureExample;
import cn.edu.zut.hkxy.service.FeatureService;
import cn.edu.zut.hkxy.util.FileUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Transactional
@Service
public class FeatureServiceImpl implements FeatureService {
    @Autowired
    private FeatureMapper featureMapper;

    @Override
    public List<Feature> getAll() {
        FeatureExample example=new FeatureExample();
        example.setOrderByClause("id asc");
        List<Feature> list = featureMapper.selectByExample(example);
        return list;
    }

    @Override
    public Boolean addFeature(MultipartFile image,Feature feature) {
        String imgName=image.getOriginalFilename();
        if (imgName==null||imgName.equals("")){
            feature.setImgurl(null);
            feature.setImgpath(null);
        }else{
            String url;
            String path;
            try {
                Map<String,String> map=FileUploadUtils.saveImgGetPath(image);
                url=map.get("url");
                path=map.get("path");
                feature.setImgpath(path);
                feature.setImgurl(url);
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        int i=featureMapper.insert(feature);
        if(i==1){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public Boolean deleteFeature(Integer id) {
        String imgPath=this.getFeatureById(id).getImgpath();
        FileUploadUtils.deleteFile(imgPath);
        int i=featureMapper.deleteByPrimaryKey(id);
        if(i==1){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public Boolean modifyFeatture(Feature feature,MultipartFile image) throws Exception {
        String imgName=image.getOriginalFilename();
        if (imgName==null||imgName.equals("")){
            //doSomething...
        }else{
            Map<String,String> map=FileUploadUtils.saveImgGetPath(image);
            String url=map.get("url");
            String path=map.get("path");
            feature.setImgpath(path);
            feature.setImgurl(url);
        }
        int i=featureMapper.updateByPrimaryKeySelective(feature);
        if(i==1){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public Feature getFeatureById(Integer id) {
        Feature feature=featureMapper.selectByPrimaryKey(id);
        return feature;
    }
}
